<!--
 * @FileDescription: 登录页
 * @Author: 周沿江
 * @Date: 2021/6/25
 * @LastEditors: 周沿江
 -->
<script>
import Logo from "../module/logo";
export default {
  components: {Logo}
}
</script>
<script src="../../utils/login_canvas.js"></script>
<template>
  <div class="login">
  <h1 style="font-family: Fangsong;font-weight: 900;margin-left: 40%;margin-top: 50px">      <logo></logo>基线检查系统</h1>
    <span style="font-family: Fangsong;font-weight: 900;margin-left: 52%;font-size: 15px;"></span>
  <div class="container" style="margin-top:40px"  align="center">
<!--注册-->
    <div class="container__form container--signup">
      <el-form :model="regiseter_Form" status-icon :rules="register_rules" ref="regiseter_Form" label-width="100px" class="form">
        <h2 class="form__title" style="margin-bottom: 30px">注 册</h2>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="regiseter_Form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass" >
          <el-input type="password" show-password v-model="regiseter_Form.pass" autocomplete="off" class="input_form"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password"show-password  v-model="regiseter_Form.checkPass" autocomplete="off"  class="input_form"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="email" >
          <el-input v-model="regiseter_Form.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn" @click="submit_register">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
<!--登录-->
    <div class="container__form container--signin">
      <el-form :model="login_Form" status-icon :rules="login_rules" ref="login_Form" label-width="60px" class="form">
        <h2 class="form__title" style="margin-bottom: 30px">登 录</h2>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="login_Form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass" >
          <el-input type="password" show-password v-model="login_Form.pass" style="width: 171px" autocomplete="off" class="input_form"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="9" :offset="1">
          <el-form-item label="验证码" prop="valid_num">
            <el-input type="text" v-model="login_Form.valid_num" maxlength="6" style="width: 70px"></el-input>
          </el-form-item>
          </el-col>
          <el-col :span="14">
            <canvas style="width: 100px;height: 33px"  width="80" height="30" id="myCanvas"></canvas>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" class="btn" @click="submit_login">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
<!--左右滑动组件-->
    <div class="container__overlay">
      <div class="overlay">
        <div class="overlay__panel overlay--left">
          <button class="btn_change" id="signIn" @click="button_change">登 录</button>
        </div>
        <div class="overlay__panel overlay--right">
          <button class="btn_change" id="signUp" @click="button_change">注 册</button>
        </div>
      </div>
    </div>
  </div>
  <h6 style="text-align:center; white-space: pre ;opacity: 0.6; color: gray;margin-top: 50px;font-size: 14px"><br>版权所有 侵权必究</h6>
  </div>
</template>
<script>
  import logo from '../../components/module/logo'
  export default {
    components:{
      logo
    },
    data(){
      // 注册用户名校验
     var checkRegisterUsername = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }else{
          if(!this.AntiSqlValid(value)){
            return callback(new Error("含有\'=;><等，请重新输入"));
          }
          setTimeout(() => {
            callback();
          }, 1000);
        }
      };
     //登录用户名校验
      var checkLoginUsername = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'));
        }else{
          if(!this.AntiSqlValid(value)){
            return callback(new Error("含有\'=;><等，请重新输入"));
          }
          setTimeout(() => {
            callback();
          }, 1000);
        }
      };
      //邮箱校验
      var checkEmail = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('邮箱不能为空'));
        }else{
          if(!this.AntiSqlValid(value)){
            return callback(new Error("含有\'=;><等，请重新输入"));
          }
          setTimeout(() => {
            callback();
          }, 1000);
        }
      };
      // 密码校验
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.regiseter_Form.checkPass !== '') {
            this.$refs.regiseter_Form.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.regiseter_Form.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        varification:'',
        login_Form:{
          pass:'',
          username:'',
          valid_num:''
        },
        regiseter_Form: {
          pass: '',
          email:'',
          checkPass: '',
          username: '',
          valid_num:''
        },
        //设置校验规则
        register_rules: {
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
          username: [
            { validator: checkRegisterUsername, trigger: 'blur' }
          ],
          email: [
            { validator: checkEmail, trigger: 'blur' }
          ]
        },
        login_rules: {
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          username: [
            { validator: checkLoginUsername, trigger: 'blur' }
          ]
        },
      }
    },
    methods:{
      /**
       * 防sql注入
       * @param value
       * @returns {boolean}
       * @constructor
       */
      AntiSqlValid(value) {
        var re = /select|update|delete|exec|count|'|"|=|;|>|<|%/i;
        if(re.test(value)) {
          // this.$message.error("含有\'=;><等，请重新输入")
          return false;
        }
        return true;
      },
      /**
       * 注册方法
       * @returns {Promise<void>}
       */
      async submit_register(){
        var data = await this.$http.post2('/shiro/register',
            {username:this.regiseter_Form.username,password:this.regiseter_Form.pass,phone:this.regiseter_Form.email});
        if(data=="success"){
          this.$message.success ('注册成功');
        }else {
          this.$message.error ('注册失败');
        }
        },
      /**
       * 登录方法
       * @returns {Promise<void>}
       */
      async submit_login(){
        if(this.varification != this.login_Form.valid_num ){
          this.$message.error('登录失败,验证码错误');
          this.$refs.login_Form.clearValidate('valid_num')
        }else{
          var data = await this.$http.post2('/shiro/login',{username:this.login_Form.username,password:this.login_Form.pass});
          if(data){
            var username = data.split("=")[0]
            var role = data.split("=")[1]
            console.log(username)
            localStorage.setItem("username",username)
            localStorage.setItem("role",role)
              this.$router.push({
                path: `/dashboard`,
              })}else{
            this.login_Form=""
            this.$message.error(data);
          }

          }


      },
      /**
       * 左右表单视图切换
       */
      button_change(){
        const signInBtn = document.getElementById("signIn");
        const signUpBtn = document.getElementById("signUp");
        const container = document.querySelector(".container");
        signInBtn.addEventListener("click", () => {container.classList.remove("right-panel-active");});
        signUpBtn.addEventListener("click", () => {container.classList.add("right-panel-active");});
      },

      /**
       * 初始化验证码
       */
      init_valid(){
          this.varification=this.randomString();
          this.cav();
          const c = document.querySelector("#myCanvas");
          c.addEventListener('click',()=>{
          this.cav();
        });
      },
      /**
       * 随机字符串生成
       * @param len
       * @returns {string}
       */
      randomString(len){
        len = len || 5;
        let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz2345678';
        let maxPos = chars.length;
        var val = '';
        for (var i = 0; i < len; i++) {
          val += chars.charAt(Math.random() * maxPos);
        }
        return val
      },
      /**
       * 随机颜色生成
       * @returns {string}
       */
      randomColor(){
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb(" + r + " , " + g + ", " + b + ")"
      },
      /**
       * 验证码生成
       */
      cav(){
        const c = document.querySelector("#myCanvas");
        console.log(c)
        this.varification = this.randomString();
        console.log(this.varification)
        const cxtwidth = c.offsetWidth;
        const cxtheight = c.offsetHeight;
        const ctx = c.getContext('2d')
        ctx.clearRect(0, 0, cxtwidth, cxtheight);
        ctx.fillStyle = 'red';
        ctx.font = '20px Arial';
        ctx.fillText(this.varification, 10, 25);
        for (var i = 0; i <= 5; i++) {
          ctx.strokeStyle = this.randomColor();
          ctx.beginPath();
          ctx.moveTo(Math.random() * cxtwidth, Math.random() * cxtheight);
          ctx.lineTo(Math.random() * cxtwidth, Math.random() * cxtheight);
          ctx.stroke()
        }

        for (var i = 0; i <= 30; i++) {
          ctx.strokeStyle = this.randomColor();
          let x = Math.random() * cxtwidth;
          let y = Math.random() * cxtheight;

          ctx.moveTo(x, y);
          ctx.lineTo(x + 1, y + 1);
          ctx.stroke()
        }
      }

    },
    //初始化
    mounted() {
      this.$nextTick(() => {
        this.init_valid();
      })
    },

  }
</script>
<style  src="../../assets/css/login.css"></style>
